import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('counter', () => {
    const username = ref('')
    const cartList = ref([])
    const seveUsername = (name) => {
            username.value = name
        }
        // 写默认
        // const cartList = ref([{
        //         "id": 1,
        //         "image": "http://dummyimage.com/200X200/f2798b",
        //         "title": "电前没所家观基资义实世该老口问其天则成因府须社因设来完先华局听导给造分路专提影万",
        //         "price": 78.28
        //     }])
        // 添加
    const addItem = (payload) => {
            const index = cartList.value.findIndex(item => item.id == payload.id)

            if (index > -1) {
                // 已存在数量加一
                cartList.value[index].count++
            } else {
                cartList.value.push({
                    ...payload,
                    count: 1,
                    checked: false
                })

            }

        }
        // 
    const delet = (id) => {
            cartList.value = cartList.value.filter(item => item.id != id)
        }
        // 订单
    const orderList = computed(() => {
        return cartList.value.filter(item => item.checked == true)
    })

    //数量
    const totalCount = computed(() => {
            let res = 0
            cartList.value.forEach(item => {
                res += item.count
            })
            return res
        })
        // 金额
    const totalPrice = computed(() => {
        let res = 0
        cartList.value.forEach(item => {
            if (item.checked == true) {
                res += item.count * item.price
            }
        })
        return res.toFixed(2)
    })

    return { username, cartList, totalCount, totalPrice, orderList, seveUsername, addItem, delet }
})